package com.idlefish.flutterboost;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import java.lang.reflect.Type;
import java.util.List;

/**
 * code by SyShare
 * 2021/1/20
 */
public class FlutterJsonUtil {

    private static Gson GSON_INSTANCE;

    public synchronized static Gson getGson() {
        if (GSON_INSTANCE == null) {
            GSON_INSTANCE = new Gson();
        }
        return GSON_INSTANCE;
    }

    public static String toJson(Object src) {
        return getGson().toJson(src);
    }
    public static <T> T fromJson(Object json, Type typeOfT) {
        return getGson().fromJson(toJson(json), typeOfT);
    }
    public static <T> T fromJson(String json, Type typeOfT) {
        return getGson().fromJson(json, typeOfT);
    }

    public static <T> T fromJson(JsonReader reader, Type typeOfT) {
        return  getGson().fromJson(reader, typeOfT);
    }

    public static <T> T fromJson(JsonElement element, Type typeOfT) {
        T t = null;
        try {
            t = getGson().fromJson(element, typeOfT);
        } catch (Exception error) {
            error.printStackTrace();
        }
        return t;
    }

    public static <T> T fromJson(JsonElement element, Class<T> classOfT) {
        T t = null;
        try {
            t = getGson().fromJson(element, classOfT);
        } catch (JsonParseException e) {
            Log.w("JsonParseException", e.getMessage());
        }
        return t;
    }

    public static <T> T fromJson(String src, Class<T> classOfT) {
        if (TextUtils.isEmpty(src)) {
            return null;
        }
        T t = null;
        try {
            t = getGson().fromJson(src, classOfT);
        } catch (JsonParseException e) {
            Log.w("JsonParseException", e.getMessage());
        }
        return t;
    }

    public static String toJson(List<?> src) {
        return getGson().toJson(src);
    }

    public static <T> T fromJson(String src, TypeToken typeToken) {
        if (TextUtils.isEmpty(src)) {
            return null;
        }
        return getGson().fromJson(src, typeToken.getType());
    }
}
